from flask import Flask, render_template, request, redirect, url_for, flash
from models import db, Student

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:123456@localhost/python_finally_work'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'ABCDEFGHIJKLMNO'

db.init_app(app)

with app.app_context():
    db.create_all()

@app.route('/')
def index():
    students = Student.query.all()
    return render_template('index.html', students=students)

@app.route('/add', methods=['GET', 'POST'])
def add_student():
    if request.method == 'POST':
        student = Student(
            Sno=request.form['Sno'],
            Sname=request.form['Sname'],
            Ssex=request.form['Ssex'],
            Sage=request.form['Sage'],
            Dno=request.form['Dno'],
            Sclass=request.form['Sclass'],
            address=request.form['address']
        )
        db.session.add(student)
        db.session.commit()
        flash('Student added successfully!')
        return redirect(url_for('index'))
    return render_template('add.html')

@app.route('/edit/<sno>', methods=['GET', 'POST'])
def edit_student(sno):
    student = Student.query.filter_by(Sno=sno).first_or_404()
    if request.method == 'POST':
        student.Sname = request.form['Sname']
        student.Ssex = request.form['Ssex']
        student.Sage = request.form['Sage']
        student.Dno = request.form['Dno']
        student.Sclass = request.form['Sclass']
        student.address = request.form['address']
        db.session.commit()
        flash('Student updated successfully!')
        return redirect(url_for('index'))
    return render_template('edit.html', student=student)

@app.route('/delete/<sno>', methods=['POST'])
def delete_student(sno):
    student = Student.query.filter_by(Sno=sno).first_or_404()
    db.session.delete(student)
    db.session.commit()
    flash('Student deleted successfully!')
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(port=5002 , debug=True)